﻿using System;
using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Workflow;
using System.Threading;
using Microsoft.SharePoint.Utilities;
using System.Globalization;
using System.Web.Script.Services;

namespace SPRA
{
    public partial class OpenMyTask : LayoutsPageBase
    {
        void responseMessage(string messageRu, string messageEn)
        {
            litError.Text = "<div style=\"width: 100%; height: 100%; vertical-align: middle; text-align: center;\">";
            litError.Text += "<p style=\"font-size: large\">" + messageRu + "<br /></p>";
            litError.Text += "<br />";
            litError.Text += "<p style=\"font-size: large\">" + messageEn + "<br /></p>";
            litError.Text += "</div>";
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string strSiteId = this.Page.Request.QueryString["SiteId"];
            string strListId = this.Page.Request.QueryString["ListId"];
            string strItemId = this.Page.Request.QueryString["ItemId"];
            string source = this.Page.Request.QueryString["Source"];

            litError.Text = "";

            string siteId = string.Empty;
            Guid listId;
            listId = Guid.Empty;
            int itemId = -1;

            try
            {
                siteId = strSiteId;
                listId = new Guid(strListId);
                if(!int.TryParse(strItemId, out itemId))
                    itemId = -1;
            }
            catch
            {
                return;
                // wrong guid
            }

            string redirectUrl = string.Empty;
            try
            {
                redirectUrl = GetUrlToRedirect(siteId, listId, itemId, source);
            }
            catch (Exception exc)
            {
                litError.Text = exc.ToString();
            }
            
            if (string.IsNullOrEmpty(redirectUrl))
                litError.Text = "There are no pending tasks";
            else
                Response.Redirect(redirectUrl);
         
        }

        private string GetUrlToRedirect(string siteId, Guid listId, int itemId, string source)
        {
            SPUserToken saUserToken = SPContext.Current.Site.SystemAccount.UserToken;
            using (SPSite spsite = new SPSite(siteId, saUserToken))
            {
                using (SPWeb spweb = spsite.OpenWeb())
                {
                    SPList list = spweb.Lists[listId];
                    SPListItem item = list.GetItemById(itemId);
                    SPUser user = SPContext.Current.Web.CurrentUser;

                    SPWorkflowManager spwflwManager = spsite.WorkflowManager;
                    SPWorkflowFilter filter = new SPWorkflowFilter(SPWorkflowState.Running, SPWorkflowState.None);
                    SPWorkflowCollection wcollection = spwflwManager.GetItemWorkflows(item, filter);

                    string completedTaskStatus = SPResource.GetString(new CultureInfo((int)SPContext.Current.Web.Language, false), "WorkflowTaskStatusComplete", new object[0]);
                    var tasks = from wf in wcollection.OfType<SPWorkflow>()
                                let allTasks = wf.Tasks.OfType<SPWorkflowTask>()
                                from wflwt in allTasks
                                let taskStatus = Convert.ToString(wflwt[SPBuiltInFieldId.TaskStatus])
                                where taskStatus != completedTaskStatus
                                let assignedTo = new SPFieldUserValueCollection(spweb, Convert.ToString(wflwt[SPBuiltInFieldId.AssignedTo]))
                                from userValue in assignedTo
                                select new { Task = wflwt, User = userValue};

                    foreach(var tuple in tasks)
                    {
                        var userValue = tuple.User;
                        var wflwt = tuple.Task;

                        if (userValue.User == null)
                        {
                            // is group
                            SPGroupCollection userGroups = user.Groups;
                            int wtGroupId = userValue.LookupId;

                            SPGroup wtUserGroup = userGroups.GetByID(wtGroupId);
                            if (!wflwt.DoesUserHavePermissions(user, SPBasePermissions.EditListItems))
                            {
                                throw new Exception("You dont have permissions to edit this task");
                            }

                            return string.Format("{0}{1}?ID={2}&IsDlg=1&Source={3}",
                                SPContext.Current.Site.Url,
                                wflwt.ParentList.DefaultEditFormUrl,
                                wflwt.ID,
                                SPHttpUtility.HtmlUrlAttributeEncode(source));
                        }
                        else
                        {
                            // is user
                            SPUser wtUser = userValue.User;
                            if (wtUser.LoginName == user.LoginName)
                            {
                                return string.Format("{0}{1}?ID={2}&IsDlg=1&Source={3}", 
                                    SPContext.Current.Site.Url, 
                                    wflwt.ParentList.DefaultEditFormUrl,
                                    wflwt.ID,
                                    SPHttpUtility.HtmlUrlAttributeEncode(source));
                            }
                        }
                    }
                }
            }
            return null;
        }
    }
}
